package com.lucanjun.cn.springsecurity.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * @author lucanjun
 * @create 2025-03-10
 * @describe MybatisPlus配置类
 */
@Configuration
public class MybatisPlusConfiguration {

    @Bean
    public MetaObjectHandler mpMetaObjectHandler() {
        return new MetaObjectHandler() {

            // 覆盖默认填充策略，原属性不为空时也会强制填充
            @Override
            public MetaObjectHandler strictFillStrategy(MetaObject metaObject, String fieldName, Supplier<?> fieldVal) {
                Object obj = fieldVal.get();
                if (Objects.nonNull(obj)) {
                    metaObject.setValue(fieldName, obj);
                }
                return this;
            }

            @Override
            public void insertFill(MetaObject metaObject) {
                this.setFieldValByName("createTime", new Date(), metaObject);
                this.setFieldValByName("updateTime", new Date(), metaObject);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                this.setFieldValByName("updateTime", new Date(), metaObject);
            }
        };
    }

}
